import 'package:flutter/material.dart';
import 'package:nim_chatkit_ui/chat_page.dart';
import 'package:nim_core/nim_core.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../common_ui/circle_avatar.dart';
import '../common_ui/empty_view.dart';
import '../model/chat_record_model.dart';
import '../refresh/custom_refresh_footer.dart';
import '../refresh/custom_refresh_header.dart';
import '../request/api.dart';
import '../request/requestManager.dart';
import '../style/box_style.dart';
import '../style/color_style.dart';
import '../style/edgeInsets_style.dart';
import '../style/text_style.dart';
import '../utils/log_utils.dart';
import '../utils/time_utils.dart';

class ChatRecordPage extends StatefulWidget {
  const ChatRecordPage({Key? key}) : super(key: key);

  @override
  State<ChatRecordPage> createState() => _ChatRecordPageState();
}

class _ChatRecordPageState extends State<ChatRecordPage> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true;
  
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final List<ChatRecordModel> _list = [];
  int _page = 1;
  int _totalPage = 1;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _list.isEmpty
        ? EmptyView()
        : SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: _page < _totalPage,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            header: CustomClassicHeader(),
            footer: const CustomClassicFooter(),
            child: ListView.builder(
              itemBuilder: ((context, index) {
                return _intimacyItem(index);
              }),
              itemCount: _list.length,
            ),
          );
  }

  Widget _intimacyItem(int index) {
    ChatRecordModel model = _list[index];
    return GestureDetector(
      child: Container(
        color: ColorStyle.whiteColor,
        padding: EdgeInsetsStyle.edgeInsets(16, 10),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CircleAvatarWidget(
                url: model.avatar ?? '', gender: model.gender ?? 1),
            Box.hBox10,
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  model.nickname ?? '',
                  style: Styles.normalText_15,
                ),
                Box.vBox5,
                Text(
                  setDesString(model.status ?? 1, model.status ?? 1,
                      callTime: model.callTime),
                  style: model.status != 4
                      ? const TextStyle(
                          fontSize: 12, color: ColorStyle.redColor)
                      : Styles.greyText_12,
                ),
              ],
            )),
            Text(
              model.createTime ?? '',
              style: Styles.greyText_12,
            ),
          ],
        ),
      ),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return ChatPage(
              sessionId: model.userid.toString(),
              sessionType: NIMSessionType.p2p);
        }));
      },
    );
  }

  String setDesString(int status, int type, {callTime}) {
    if (status == 1) {
      if (type == 1) {
        return '自己取消';
      } else {
        return '对方取消';
      }
    } else if (status == 2) {
      if (type == 1) {
        return '对方拒绝';
      } else {
        return '自己拒绝';
      }
    } else if (status == 3) {
      return '超时未接听';
    } else if (status == 4) {
      return '视频时长:${TimeUtils.getTimeStrFromSS(callTime)}';
    }
    return '';
  }

  @override
  void initState() {
    super.initState();
    loadNewList();
  }

  void loadNewList() async {
    var result = await RequestManager()
        .post(API.callList, params: {'page': _page, 'calltype': 0, 'type': 0});
    if (result != null && result['code'] == 0) {
      WJLogUtils.wjLog(result);
      _list.clear();
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      List tempList = result['data']['list'];
      for (var element in tempList) {
        ChatRecordModel m = ChatRecordModel.fromJson(element);
        _list.add(m);
      }
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.fansList, params: {'type': 0, 'page': _page, 'calltype': 0});

    if (result != null && result['code'] == 0) {
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      List tempList = result['data']['list'];
      _list.addAll(tempList.map((e) {
        ChatRecordModel m = ChatRecordModel.fromJson(e);
        return m;
      }));
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _onRefresh() {
    _page = 1;
    _totalPage = 1;
    loadNewList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _page += 1;
    loadMoreList();
    _refreshController.loadComplete();
  }
}
